<template>
  <div class="map">
    <!-- 顶部 -->
    <van-nav-bar
      left-arrow
      title="请选择地址"
      :border=false
      :fixed=true
      @click-left="onClickLeft"
      style="height: 44px">
    </van-nav-bar>
    <!-- 地图部分 -->
    <div class="a-map">
      <div class="amap-page-container">
        <el-amap
          ref="map"
          vid="amapDemo"
          :plugin="plugin"
          :zoom="zoom"
          :center="center"
          class="amap-map"
          :events="events"
          v-show="showMap"
        >
          <el-amap-marker
            vid="component-marker"
            :position="makerConf.position"
            :content="makerConf.content" />
        </el-amap>
      </div>
    </div>
    <scroll
      class="wrap"
      :scrollY="true"
      :listenScroll="true"
      :probeType="3"
      :data="list">
      <div class="address-list">
        <ul v-if="list.length > 0">
          <!-- 当前位置 -->
          <van-cell-group title="当前地址">
            <van-cell>
              <template #title>
                <div class="custom-title">
                  <p class="title">{{list[0].name}}</p>
                  <p class="subtitle">{{list[0].address}}</p>
                </div>
              </template>
            </van-cell>
          </van-cell-group>
          <!-- 附近位置 -->
          <van-cell-group title="附近地址">
            <ul>
              <li
              class="near-list"
              v-for="(item ,index) in list"
              :key="index"
              @click="clickAddress(item)"
              >
                <p class="title">{{item.name}}</p>
                <p class="subtitle">{{item.address}}</p>
              </li>
            </ul>
          </van-cell-group>
        </ul>
      </div>
    </scroll>
  </div>
</template>

<script>
import Vue from 'vue'
import VueAMap from 'vue-amap'
import PubSub from 'pubsub-js'
import { LOCATION_ADDRESS } from '../../config/pubsub-type'
import { setLocalStore } from '../../config/global'

Vue.use(VueAMap)
VueAMap.initAMapApiLoader({
  // 申请的高德key
  key: 'cde7aa4cab0681d34ddb6916431125b2',
  // 插件集合所有的
  plugin: [
    'AMap.Autocomplete', 'AMap.PlaceSearch',
    'AMap.Scale', 'AMap.OverView',
    'AMap.ToolBar', 'AMap.MapType',
    'AMap.PolyEditor', 'AMap.CircleEditor', 'AMap.Geolocation'
  ],
  uiVersion: '1.0',
  v: '1.4.4'
})
export default {
  name: 'Map',
  data () {
    const self = this
    self.city = self.city || '苏州'
    return {
      showMap: true,
      list: [],
      currentLocation: [],
      currentIndex: 0,
      zoom: 16,
      center: [114.397169, 30.50576],
      events: {
        init: (o) => {
          o.setCity(self.city, result => {
            self.center = result
            if (result && result.length > 0) {
              self.zoom = 16
              self.makerConf.position = result
              self.getList(result)
            }
          })
          this.$nextTick(() => {
            //去掉logo
            document.getElementsByClassName('amap-logo')[0].style.display = 'none'
            // 去掉版权信息
            document.getElementsByClassName('amap-copyright')[0].style.opacity = '0'
            // 修改搜索结果框的宽度
            // document.getElementsByClassName('search-tips')[0].style.width = '60%';
            // 隐藏比例尺
            document.getElementsByClassName('amap-scalecontrol')[0].style.visibility = 'hidden'
            // 修改定位当前位置
            document.getElementsByClassName('amap-geolocation-con')[0].style.left = '85%'
          })
        },
        // 拖拽
        dragend (e) {
          const point = this.getCenter()
          const pos = [point.lng, point.lat]
          this.makerConf.position = [point.lng, point.lat]
          this.getList(pos)
        }
      },
      makerConf: {
        position: [114.397169, 30.50576],
        content: ''
      },
      searchOption: {
        city: self.city,
        citylimit: true
      },
      plugin: [
        'Scale',
        {
          pName: 'Geolocation',
          events: {
            init (o) {
              // 获取当前位置
              o.getCurrentPosition((status, result) => {
                if (result && result.position) {
                  self.lng = result.position.lng
                  self.lat = result.position.lat
                  self.center = [self.lng, self.lat]
                  self.loaded = true
                  self.$nextTick()
                }
              })
            },
            complete (result) {
              //定位成功
              const address = result.formattedAddress
              const point = result.position;
              const obj = {
                address: address,
                name: '',
                location: point
              }
              self.makerConf.position = [point.lng, point.lat]
              self.getList([point.lng, point.lat])
            },
            error () {
            }
          }
        }
      ]
    }
  },
  methods: {
    // 获取位置列表
    getList (result) {
      const self = this
      self.$Geocoder({
        lnglatXY: result,
        success (res) {
          self.list = (res.regeocode && res.regeocode.pois) ? res.regeocode.pois : []
        },
        error (res) {
          self.list = []
        }
      })
    },
    // 搜索结果
    onSearchResult () {
      const latSum = 0
      const lngSum = 0
      const me = this
      const mymap = me.$refs.$$getInstance()
      if (pois && pois.length > 0) {
        const poi = pois[0]
        const lng = poi['lng']
        const lat = poi['lat']
        me.center = [lng, lat]
        me.makerConf.position = [lng, lat]
        me.makerConf.content = poi.name
        me.list = pois
      } else {
        me.list = []
      }
    },
    //将坐标转化为实际地址
    $Geocoder (options = {}) {
      if (AMap) {
        AMap.plugin(['AMap.Geocoder'], () => {
          const geocoder = new AMap.Geocoder({
            radius: options.radius || 1000,
            extensions: options.extensions || 'all'
          })
          const lnglatXY = options.lnglatXY || [114.397169, 30.50576] //已知点坐标
          geocoder.getAddress(lnglatXY, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              options.success && options.success(result)
            } else {
              options.error && options.error(status, result)
            }
          })
        })
      }
    },
    onClickLeft () {
      this.$router.back()
    },
    clickAddress(item) {
      // 发通知给Header组件修改名称
      PubSub.publish(LOCATION_ADDRESS, item.name)
      setLocalStore('userLocation', item.name)
      this.$router.back()
    }
  },
  watch:{
    list () {
      this.currentIndex = 0
    }
  }
}

</script>
<style lang='scss' scoped>
.map {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  @include setWH(100%, 100%);
  z-index: 200;
  background: #f5f5f5;
  .amap-map {
    height: px2rem(175);
    .amap-page-container {
      margin-top: px2rem(52);
      height: px2rem(175);
    }
    .amap-geolocation-con {
      bottom: px2rem(35) !important;
      z-index: 100 !important;
    }
  }
  .wrap {
    overflow: hidden;
    height: calc(100vh - 44px - 175px + 40px);
  }
  .address-list {
    width: 100%;
    overflow:hidden;
    .title {
      font-size: px2rem(14);
      color: #000;
    }
    .subtitle {
      font-size: px2rem(10);
      color: grey;
    }
    .near-list {
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      height: px2rem(68);
      line-height: px2rem(17.5);
      padding-top: px2rem(17.5);
      padding-left: px2rem(17.5);
      border-bottom: 0.1px solid #dedede;
    }
  }
}
</style>
